package com.handu.luna.mall.controller;

import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import com.handu.luna.core.domain.user.User;
import com.handu.luna.core.domain.user.UserRepository;

@Service
public class SessionUser {
	
	@Autowired
	private StringRedisTemplate template;

	@Autowired
	private UserRepository userRepository;
	
	private String id;

	public SessionUser getOrCreateSession(String sessionId){
		SessionUser session = new SessionUser();
		session.setTemplate(template);
		session.setUserRepository(userRepository);
		if(sessionId == null){
			session.id = UUID.randomUUID().toString();
		}else{
			session.id = sessionId;
		}
		return session;
	}


	public StringRedisTemplate getTemplate() {
		return template;
	}

	public void setTemplate(StringRedisTemplate template) {
		this.template = template;
	}

	public UserRepository getUserRepository() {
		return userRepository;
	}

	public void setUserRepository(UserRepository userRepository) {
		this.userRepository = userRepository;
	}


	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}
	
	public User user;


	public void setUser(User user) {
		ValueOperations<String, String> ops = template.opsForValue();
		ops.set(id, user.getId().toString());
		//this.user = user;
	}
	
	/**
	 * 得到当前会话的操作员，如果无法得到则返回null
	 * @return 得到当前会话的操作员，如果无法得到则返回null
	 */
	public User getUser() {
		long userId = getUserId();
		if(userId == 0){
			return null;
		}else{
			return userRepository.findOne(userId);
		}
		
	}
	
	private long getUserId() {
		ValueOperations<String, String> ops = template.opsForValue();
		if(template.hasKey(id)){
			return Long.parseLong(ops.get(id));
		}else{
			return 0;
		}
	}

}
